package io.gitee.zhangbinhub.acp.cloud

import io.gitee.zhangbinhub.acp.boot.http.HttpStatus
import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import io.gitee.zhangbinhub.acp.cloud.tools.CloudTools
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import org.noear.nami.NamiConfiguration
import org.noear.solon.annotation.Bean
import org.noear.solon.annotation.Configuration
import org.noear.solon.annotation.Inject

/**
 * @since JDK 17
 */
@Configuration
class AcpCloudNamiAutoConfiguration {
    @Bean
    fun namiConfiguration(@Inject logAdapter: LogAdapter): NamiConfiguration = NamiConfiguration { client, builder ->
        builder.filterAdd { invocation ->
            invocation?.headers?.putAll(CloudTools.transmitHeaders())
            try {
                invocation?.invoke().let { result ->
                    if (result != null && result.code() >= HttpStatus.BAD_REQUEST.value()) {
                        logAdapter.error(
                            "Remoting ${client.name} Error[${result.code()}]: ${
                                String(
                                    result.body(),
                                    CommonTools.getDefaultCharset()
                                )
                            }"
                        )
                        null
                    } else {
                        result
                    }
                }
            } catch (e: Throwable) {
                logAdapter.error(e.message, e)
                null
            }
        }
    }
}
